<template>
  <!-- 温度分布统计 -->
  <div class="chartContent">
    <a-form :model="form" layout="inline" ref="formRef" class="chartForm">
      <a-form-item label="日期" name="code">
        <a-date-picker
          v-model:value="form.date"
          placeholder="选择日期"
          class="formSelect"
          formatter="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :allowClear="false"
        />
      </a-form-item>
      <a-form-item label="显示维度" name="name">
        <a-select
          ref="select"
          v-model:value="chartType"
          class="formSelect"
          placeholder="请选择"
          @change="changeChartType"
          style="width: 120px"
        >
          <a-select-option
            v-for="item in chartTypeList"
            :value="item.value"
            :key="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="电池堆">
        <a-select
          ref="select"
          v-model:value="form.linkId"
          class="formInput"
          allow-clear
          placeholder="请选择"
          :disabled="chartType === 3"
          @change="changeLink"
        >
          <a-select-option
            v-for="item in energyLinkList"
            :value="item.deviceId"
            :key="item.deviceId"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="电池簇">
        <a-select
          ref="select"
          v-model:value="form.equipId"
          class="formInput"
          allow-clear
          placeholder="请选择"
          :disabled="chartType !== 1"
        >
          <a-select-option
            v-for="item in blockList"
            :value="item.deviceId"
            :key="item.deviceId"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-button
        type="primary"
        class="filterBtn"
        @click="handleQuery"
        :loading="chartLoading"
        >查询</a-button
      >
      <a-button
        v-if="chartType === 1"
        type="primary"
        class="filterBtn yellowBtn"
        @click="checkData"
        >查看数据</a-button
      >
    </a-form>

    <a-spin :spinning="chartLoading">
      <!-- 电池簇维度：显示温度分布统计图表 -->
      <div
        v-show="activeView === 1"
        class="chartContainer"
        ref="temperatureDistributionChartRef"
      ></div>
      
      <!-- 非电池簇维度：显示Temperature组件 -->
      <Temperature 
        v-show="activeView !== 1"
        ref="temperatureRef"
        :stationInfo="stationInfo"
        :externalParams="temperatureParams"
        @loading-change="handleTemperatureLoading"
      />
    </a-spin>
  </div>
  
  <!-- 查看数据 -->
  <DetailsData
    v-if="chartType === 1"
    :detailsDataVisible="detailsDataVisible"
    :chartsTableData="chartsTableData"
    :chartType="chartType"
    :deviceName="currentDeviceName"
    @update:detailsDataVisible="(val) => (detailsDataVisible = val)"
  />
</template>
<script setup>
;
import { commonConfigStore } from "@/stores/commonConfig";
import DetailsData from "./detailsData.vue";
import Temperature from "./temperature/index.vue";
import * as echarts from "echarts";
import { getVoltageDistributionOption } from "./chartOption";
import { getCurrentDate, getYesterdayFromDate } from "@/utils/common";


const props = defineProps({
  stationInfo: {
    type: Object,
    required: true,
  },
});

const $api = inject("$api");
const temperatureRef = ref(null);

// 表单数据
const form = ref({
  date: null,
  linkId: null,
  equipId: null,
});

// 图表相关
const chartType = ref(null);
const activeView = ref(null); // 控制实际显示的组件，避免切换维度时立即隐藏图表
const temperatureDistributionChartRef = ref(null);
const voltageChart = ref(null);
const chartsData = ref([]);
const chartLoading = ref(false);
const energyLinkList = ref([]);
const blockList = ref([]);
const detailsDataVisible = ref(false);
const chartsTableData = ref([]);
const currentDeviceName = ref("");

// 图表类型列表
const chartTypeList = ref([
  {
    value: 1,
    label: "电池簇",
  },
  {
    value: 2,
    label: "电池堆",
  },
  {
    value: 3,
    label: "电站",
  },
]);
// 传递给Temperature组件的参数
const temperatureParams = computed(() => ({
  chartType: chartType.value,
  date: form.value.date,
  linkId: form.value.linkId,
  equipId: form.value.equipId,
  energyLinkList: energyLinkList.value,
  blockList: blockList.value,
}));

const handleTemperatureLoading = (loading) => {
  chartLoading.value = loading;
};

const forceResizeChart = () => {
  if (voltageChart.value) {
    nextTick(() => {
      setTimeout(() => {
        voltageChart.value.resize();
      }, 100);
    });
  }
};

// 统一的查询处理
const handleQuery = async () => {
  if (!form.value.date) {
    message.warning("请选择日期");
    return;
  }
  
  if (!chartType.value) {
    message.warning("请选择显示维度");
    return;
  }

  activeView.value = chartType.value;

  if (chartType.value === 1) {
    await nextTick();
    await getTemperatureData();
  } else {
    if (voltageChart.value) {
      voltageChart.value.dispose();
      voltageChart.value = null;
    }
    
    if (temperatureRef.value && temperatureRef.value.getTempData) {
      await nextTick();
      await temperatureRef.value.getTempData();
    }
  }
};

onUnmounted(() => {
  if (voltageChart.value) {
    voltageChart.value.dispose();
  }
  window.removeEventListener("resize", handleResize);
});

const handleResize = () => {
  if (voltageChart.value) {
    voltageChart.value.resize();
  }
};

watch(
  () => voltageChart.value,
  (newChart) => {
    if (newChart) {
      window.addEventListener("resize", handleResize);
    }
  }
);

// 初始化图表
const initChart = () => {
  if (!temperatureDistributionChartRef.value) {
    console.warn("图表容器DOM元素不存在");
    return;
  }

  // 如果已有图表实例，先销毁
  if (voltageChart.value) {
    voltageChart.value.dispose();
    voltageChart.value = null;
  }

  const chartInstance = echarts.init(temperatureDistributionChartRef.value);
  if (chartInstance) {
    chartInstance.clear();
    const option = getVoltageDistributionOption(chartType.value || 1, {});
    chartInstance.setOption(option);
    voltageChart.value = markRaw(chartInstance);

    // 延迟调用resize确保容器尺寸已确定
    nextTick(() => {
      setTimeout(() => {
        if (voltageChart.value) {
          voltageChart.value.resize();
        }
      }, 100);
    });
  }
};
// 切换电池堆
const changeLink = async (id) => {
  form.value.equipId = null;
  await getBlockList(id);
  
  // 如果当前是电池簇维度，设置默认的电池簇
  if (chartType.value === 1) {
    form.value.equipId = blockList.value?.[0]?.deviceId;
  }
};
const getBlockList = async (id) => {
  const params = {
    stationId: props.stationInfo.id,
    linkId: id,
  };
  const res = await $api.powerBlockList(params);
  if (res && res.code === 0) {
    blockList.value = res.data;
    if (chartType.value === 1) {
      form.value.equipId = blockList.value?.[0]?.deviceId;
    }
  }
};
const getTempDimension = async () => {
  const res = await $api.temperatureDimension({
    stationId: props.stationInfo.id,
  });
  if (res?.code === 0) {
    chartTypeList.value = chartTypeList.value.filter((item) =>
      res.data.includes(item.value)
    );
    chartType.value = chartTypeList.value[0].value;
    activeView.value = chartType.value; // 初始化activeView
    await changeChartType(); // 处理维度、电池堆、电池簇联动
    if (chartType.value === 1) {
      // 电池簇维度才进入这个请求，其余维度用之前的temperature页面
      getTemperatureData();
    }
  }
};
const changeChartType = async () => {
  form.value.linkId = null;
  form.value.equipId = null;
  
  switch (chartType.value) {
    case 1:
      // 电池簇维度
      form.value.linkId = energyLinkList.value?.[0]?.deviceId;
      await getBlockList(form.value.linkId);
      form.value.equipId = blockList.value?.[0]?.deviceId;
      break;
    case 2:
      // 电池堆维度
      form.value.linkId = energyLinkList.value?.[0]?.deviceId;
      break;
    case 3:
      // 电站维度
      break;
  }
  
  // 等待下一个tick，确保Temperature组件已经渲染
  await nextTick();
  
  // 如果是非电池簇维度，同步参数到Temperature组件
  if (chartType.value !== 1 && temperatureRef.value) {
    // 调用Temperature组件的changeChartType方法
    if (temperatureRef.value.changeChartType) {
      await temperatureRef.value.changeChartType();
    }
  }
};
// 获取温度数据
const getTemperatureData = async () => {
  if (!form.value.date) {
    message.warning("请选择日期");
    return;
  }

  if (!chartType.value) {
    message.warning("请选择显示维度");
    return;
  }

  if (chartType.value !== 1) {
    // 电池簇维度才进入这个请求，其余维度用之前的temperature页面
    return;
  }

  chartLoading.value = true;

  // 获取今日数据
  const todayDataPromises = [];

  // 根据chartType确定参数
  const baseParams = {
    stationId: props.stationInfo.id,
    dimensionType: chartType.value,
    date: form.value.date,
  };
  // 根据显示维度设置组件ID
  if (chartType.value === 1 && form.value.equipId) {
    // 电池簇
    baseParams.componentId = form.value.equipId;
  } else if (chartType.value === 2 && form.value.linkId) {
    // 电池堆
    baseParams.componentId = form.value.linkId;
  }
  // 获取最高温度、最低温度数据
  todayDataPromises.push(
    $api.temperatureData({ ...baseParams, lineType: 2 }), // 最高温度
    $api.temperatureData({ ...baseParams, lineType: 1 }) // 最低温度
  );
  // 获取昨日数据用于对比
  const yesterdayDate = getYesterdayFromDate(form.value.date);
  const yesterdayParams = { ...baseParams, date: yesterdayDate };
  todayDataPromises.push(
    $api.temperatureData({ ...yesterdayParams, lineType: 2 }), // 昨日最高温度
    $api.temperatureData({ ...yesterdayParams, lineType: 1 }) // 昨日最低温度
  );
  const [todayMaxRes, todayMinRes, yesterdayMaxRes, yesterdayMinRes] =
    await Promise.all(todayDataPromises);

  // 如果是电池簇维度，需要先获取时段数据再更新图表
  if (chartType.value === 1 && form.value.equipId) {
    await getTemperatureScope();
  }

  chartLoading.value = false;
  // 处理返回数据
  const processedData = processTemperatureData(
    todayMaxRes?.data || [],
    todayMinRes?.data || [],
    yesterdayMaxRes?.data || [],
    yesterdayMinRes?.data || []
  );

  // 等待DOM更新后再更新图表
  await nextTick();
  updateChart(processedData);

  // 保存数据用于"查看数据"功能
  chartsData.value = {
    today: {
      max: todayMaxRes?.data || [],
      min: todayMinRes?.data || [],
    },
    yesterday: {
      max: yesterdayMaxRes?.data || [],
      min: yesterdayMinRes?.data || [],
    },
  };
};

// 处理温度数据
const processTemperatureData = (
  todayMaxData,
  todayMinData,
  yesterdayMaxData,
  yesterdayMinData
) => {
  const maxTemperatureData = [];
  const minTemperatureData = [];
  const diffData = [];
  const yesterdayMaxTemperatureData = [];
  const yesterdayMinTemperatureData = [];
  const yesterdayDiffData = [];
  
  // 构建tooltipData
  const tooltipData = {};

  // 获取最长的数据长度
  const maxLength = Math.max(
    todayMaxData.length > 0 ? todayMaxData[0]?.lineData?.length || 0 : 0,
    todayMinData.length > 0 ? todayMinData[0]?.lineData?.length || 0 : 0,
    yesterdayMaxData.length > 0 ? yesterdayMaxData[0]?.lineData?.length || 0 : 0,
    yesterdayMinData.length > 0 ? yesterdayMinData[0]?.lineData?.length || 0 : 0
  );

  // 处理今日数据
  const todayMaxLine =
    todayMaxData.length > 0 ? todayMaxData[0]?.lineData || [] : [];
  const todayMinLine =
    todayMinData.length > 0 ? todayMinData[0]?.lineData || [] : [];

  // 处理昨日数据
  const yesterdayMaxLine =
    yesterdayMaxData.length > 0 ? yesterdayMaxData[0]?.lineData || [] : [];
  const yesterdayMinLine =
    yesterdayMinData.length > 0 ? yesterdayMinData[0]?.lineData || [] : [];

  // 获取位置信息
  const todayMaxInfo = todayMaxData.length > 0 ? todayMaxData[0] : {};
  const todayMinInfo = todayMinData.length > 0 ? todayMinData[0] : {};

  for (let i = 0; i < maxLength; i++) {
    // 今日数据
    const todayMaxTemp = todayMaxLine[i]?.value || null;
    const todayMinTemp = todayMinLine[i]?.value || null;
    const todayDiff = (todayMaxTemp !== null && todayMinTemp !== null) ? 
      (todayMaxTemp - todayMinTemp).toFixed(2) : null;
    maxTemperatureData.push(todayMaxTemp);
    minTemperatureData.push(todayMinTemp);
    diffData.push(todayDiff);

    // 昨日数据
    const yesterdayMaxTemp = yesterdayMaxLine[i]?.value || null;
    const yesterdayMinTemp = yesterdayMinLine[i]?.value || null;
    const yesterdayDiff = (yesterdayMaxTemp !== null && yesterdayMinTemp !== null) ? 
      (yesterdayMaxTemp - yesterdayMinTemp).toFixed(2) : null;

    yesterdayMaxTemperatureData.push(yesterdayMaxTemp);
    yesterdayMinTemperatureData.push(yesterdayMinTemp);
    yesterdayDiffData.push(yesterdayDiff);
    
    // 构建tooltipData（使用时间作为key）
    // 优先使用今日数据的时间，如果没有则使用昨日数据的时间，都没有则生成时间
    let time;
    if (todayMaxLine[i]?.dateTime) {
      time = todayMaxLine[i].dateTime.substring(11, 16); // 提取HH:MM格式时间
    } else if (yesterdayMaxLine[i]?.dateTime) {
      time = yesterdayMaxLine[i].dateTime.substring(11, 16); // 提取HH:MM格式时间
    } else {
      // 如果没有时间数据，根据索引生成时间
      const hour = Math.floor(i / 60);
      const minute = i % 60;
      time = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
    }
    
    tooltipData[time] = {
      max: {
        value: todayMaxTemp,
        linkName: todayMaxInfo.linkName || '',
        blockName: todayMaxInfo.blockName || ''
      },
      min: {
        value: todayMinTemp,
        linkName: todayMinInfo.linkName || '',
        blockName: todayMinInfo.blockName || ''
      },
      yesterdayMax: {
        value: yesterdayMaxTemp,
        linkName: todayMaxInfo.linkName || '',
        blockName: todayMaxInfo.blockName || ''
      },
      yesterdayMin: {
        value: yesterdayMinTemp,
        linkName: todayMinInfo.linkName || '',
        blockName: todayMinInfo.blockName || ''
      }
    };
  }

  return {
    maxVoltageData: maxTemperatureData, // 复用原有字段名，实际是温度数据
    minVoltageData: minTemperatureData,
    diffData,
    yesterdayMaxVoltageData: yesterdayMaxTemperatureData,
    yesterdayMinVoltageData: yesterdayMinTemperatureData,
    yesterdayDiffData,
    tooltipData,
  };
};

// 更新图表
const updateChart = (data) => {
  // 确保DOM元素存在
  if (!temperatureDistributionChartRef.value) {
    console.warn("图表容器DOM元素不存在，无法更新图表");
    return;
  }

  if (!voltageChart.value) {
    initChart();
    if (!voltageChart.value) return;
  }

  const option = getVoltageDistributionOption(chartType.value, data.tooltipData || {});

  if (option.series && option.series.length >= 6) {
    // 今日数据
    option.series[0].data = data.maxVoltageData || []; // 今日最高温度
    option.series[1].data = data.minVoltageData || []; // 今日最低温度
    option.series[2].data = data.diffData || []; // 今日最大温差

    // 昨日数据
    option.series[3].data = data.yesterdayMaxVoltageData || []; // 昨日最高温度
    option.series[4].data = data.yesterdayMinVoltageData || []; // 昨日最低温度
    option.series[5].data = data.yesterdayDiffData || []; // 昨日最大温差
  }
  if (chartType.value === 1) {
    const markAreaData = [];
    // 提取时间部分的函数（从 "2025-07-10 00:01:00" 提取 "00:01"）
    const extractTime = (dateTimeStr) => {
      const time = dateTimeStr.split(" ")[1];
      return time.substring(0, 5);
    };
    // 添加制冷时间段
    if (timeRange.value) {
      timeRange.value.forEach((chargeTime) => {
        // 计算时间区间长度（小时）
        const beginTime = new Date(chargeTime.beginTime);
        const endTime = new Date(chargeTime.endTime);
        const timeDiffHours = (endTime - beginTime) / (1000 * 60 * 60);
        // 只有当时间区间大于1小时时才显示"制冷"字样
        const displayName = timeDiffHours > 1 ? "制冷" : "";
        markAreaData.push([
          {
            name: displayName,
            xAxis: extractTime(chargeTime.beginTime),
            itemStyle: {
              color: "rgba(91, 143, 249, 0.09)",
              borderColor: "rgba(25, 25, 112, 0.6)",
              borderWidth: 1,
            },
          },
          {
            xAxis: extractTime(chargeTime.endTime),
          },
        ]);
      });
    }
    const arr = [0, 2];
    arr.forEach((item) => {
      option.series[item].markArea = {
        silent: true,
        label: {
          show: true,
          color: "#ffffff",
          fontSize: 12,
          fontWeight: "bold",
          textShadowColor: "rgba(0,0,0,0.8)",
          textShadowBlur: 2,
          textShadowOffsetX: 1,
          textShadowOffsetY: 1,
        },
        itemStyle: {
          color: "rgba(139, 69, 19, 0.2)",
          borderColor: "rgba(139, 69, 19, 0.6)",
          borderWidth: 1,
        },
        data: markAreaData,
      };
    });
  }

  // 使用notMerge参数确保完整更新
  voltageChart.value.setOption(option, true);
};

// 处理数据为表格格式
const processDataForTable = (data) => {
  const tableData = [];

  // 获取今日和昨日的最高温度和最低温度数据
  const todayMaxData = data.today?.max?.[0]?.lineData || [];
  const todayMinData = data.today?.min?.[0]?.lineData || [];
  const yesterdayMaxData = data.yesterday?.max?.[0]?.lineData || [];
  const yesterdayMinData = data.yesterday?.min?.[0]?.lineData || [];

  // 使用最长的数据长度
  const maxLength = Math.max(
    todayMaxData.length,
    todayMinData.length,
    yesterdayMaxData.length,
    yesterdayMinData.length
  );

  for (let i = 0; i < maxLength; i++) {
    const todayMaxItem = todayMaxData[i];
    const todayMinItem = todayMinData[i];
    const yesterdayMaxItem = yesterdayMaxData[i];
    const yesterdayMinItem = yesterdayMinData[i];

    if (todayMaxItem || todayMinItem || yesterdayMaxItem || yesterdayMinItem) {
      // 生成时间（根据索引生成HH:mm格式）
      const hour = Math.floor(i / 60);
      const minute = i % 60;
      const time = `${hour.toString().padStart(2, "0")}:${minute
        .toString()
        .padStart(2, "0")}`;

      // 今日数据
      const todayMaxTemp = todayMaxItem?.value || 0;
      const todayMinTemp = todayMinItem?.value || 0;
      const todayDiff = todayMaxTemp - todayMinTemp;

      // 昨日数据
      const yesterdayMaxTemp = yesterdayMaxItem?.value || 0;
      const yesterdayMinTemp = yesterdayMinItem?.value || 0;
      const yesterdayDiff = yesterdayMaxTemp - yesterdayMinTemp;

      tableData.push({
        time: time,
        todayMaxTemperature: todayMaxTemp,
        todayMinTemperature: todayMinTemp,
        todayDiff: todayDiff,
        yesterdayMaxTemperature: yesterdayMaxTemp,
        yesterdayMinTemperature: yesterdayMinTemp,
        yesterdayDiff: yesterdayDiff,
      });
    }
  }

  return tableData;
};

// 查看数据
const checkData = () => {
  if (
    !chartsData.value ||
    (!chartsData.value.today?.max?.length &&
      !chartsData.value.today?.min?.length)
  ) {
    message.warning("暂无数据");
    return;
  }
  // 获取当前选中的设备名称
  let deviceName = blockList.value.find(
    (item) => item.deviceId === form.value.equipId
  )?.name;
  currentDeviceName.value = deviceName;
  // 转换数据格式为与voltageDistribution一致的格式
  const processedTableData = processDataForTable(chartsData.value);
  chartsTableData.value = processedTableData;
  detailsDataVisible.value = true;
};
const getEnergyLinkList = async () => {
  // 获取电池堆列表 如果不是主电池堆，需要拉取电池堆列表指定所属
  const res = await $api.energyLinkList({
    current: 1,
    size: 10000,
    stationId: props.stationInfo.id,
  });
  energyLinkList.value = res?.data;
};
const timeRange = ref([]);
const getTemperatureScope = async () => {
  const params = {
    stationId: props.stationInfo.id,
    blockId: form.value.equipId,
    date: form.value.date,
  };
  const res = await $api.temperatureScope(params);
  if (res && res.code === 0) {
    timeRange.value = res.data;
  }
};
const handleChageStation = async () => {
  form.value.date = getCurrentDate();
  chartType.value = 1; // 默认选择电池簇
  activeView.value = 1; // 初始化activeView
  await getEnergyLinkList();
  await getTempDimension();
  
  // 等待下一个tick，确保组件已经渲染
  await nextTick();
  
  // 如果Temperature组件存在，也初始化它
  if (temperatureRef.value && temperatureRef.value.handleChageStation) {
    await temperatureRef.value.handleChageStation();
  }
};

defineExpose({ 
  handleChageStation,
  forceResizeChart
});
</script>

<style lang="less" scoped>
.chartForm {
  margin-top: 20px;
}
.ant-form-item {
  margin-bottom: 20px;
}
.formInput {
  width: 180px;
}
.chartContainer {
  margin-bottom: 20px;
  width: 100%;
  height: 500px;
  background: #141414;
  border-radius: 4px;
}
.filterBtn {
  margin-right: 20px;
}
</style>
